/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package th.manager;

import com.google.inject.Inject;
import com.wideplay.warp.persist.Transactional;
import java.util.Date;
import java.util.List;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import th.dao.KodKebenaranTransaksiDAO;
import th.dao.SmsDAO;
import th.model.KodKebenaranTransaksi;
import th.model.Sms;
import th.stripes.Configuration;

/**
 *
 * @author ubuntu
 */
public class SMSgatewayManager {
    
    @Inject
    protected com.google.inject.Provider<Session> sessionProvider;
    @Inject 
    private KodKebenaranTransaksiDAO kodKebenaranTransaksiDAO;
    @Inject
    Configuration conf;
    
    @Inject
    private SmsDAO smsDAO;
    
    private static final int TIMEOUT = 30 * 60 * 1000;
    
    private static Logger LOG = LoggerFactory.getLogger(SMSgatewayManager.class);
        
    @Transactional
    public void saveTAC(KodKebenaranTransaksi kodKebenaranTransaksi) {
        kodKebenaranTransaksiDAO.save(kodKebenaranTransaksi);
    }
    
    @Transactional
    public void deleteTAC(KodKebenaranTransaksi kodKebenaranTransaksi) {
        kodKebenaranTransaksiDAO.delete(kodKebenaranTransaksi);
    }
    
    public KodKebenaranTransaksi findKodKebenaranTransaksiByPengguna(String pguna, String operasi) {        
        String query = "SELECT a FROM KodKebenaranTransaksi a WHERE a.infoAudit.dimasukOleh.idPengguna= :pguna AND a.operasi = :operasi";
        KodKebenaranTransaksi q = (KodKebenaranTransaksi)sessionProvider.get().createQuery(query).setString("operasi", operasi.toString()).setString("pguna", pguna.toString()).uniqueResult();
        return q;
    } 
    
    public KodKebenaranTransaksi findKodKebenaranTransaksiBySessionId(String idSessi, String operasi, String sah) {        
        String query = "SELECT a FROM KodKebenaranTransaksi a WHERE a.idSessi = :idSessi AND a.operasi = :operasi AND a.sah = :sah";
        KodKebenaranTransaksi q = (KodKebenaranTransaksi)sessionProvider.get().createQuery(query).setString("operasi", operasi.toString()).setString("idSessi", idSessi.toString()).setString("sah", sah.toString()).uniqueResult();
        return q;
    }
    
    public List<Sms> smsReport( String date, String noPhone, String status) {
        StringBuilder sb = new StringBuilder("SELECT s from Sms s where date(s.tarikhHantar) = :date ");
        if (StringUtils.isNotBlank(noPhone)) {
            sb.append("AND s.noTel = :noPhone ");
        }
        if (StringUtils.isNotBlank(status)) {
            sb.append("AND s.deliveryNotification = :status");
        }
        
       Session session = sessionProvider.get();
        Query query = session.createQuery(sb.toString()).setString("date", date);
        if (StringUtils.isNotBlank(noPhone)) {
              query.setString("noPhone", noPhone); 
        }
        if (StringUtils.isNotBlank(status)) {
              query.setString("status", status); 
        }
        return query.list();   
    }
    
    public String sendSMS(String phoneNo, String content) {
        
        String result = "";
        if(phoneNo!=null && phoneNo.length()>0 && phoneNo.trim().charAt(0) == '0'){
            phoneNo = "6"+phoneNo;            
        }
        //todo : proper code
        StringBuilder cmd = new StringBuilder("https://secure.etracker.cc/LembagaTabungHaji/TACService.svc/tac")
                .append("?user=lthtac")
                .append("&pass=lthtac123")
                .append("&msisdn=")
                .append(phoneNo)
                .append("&message=")
                .append(content);
        try {
            
            HttpClient client = new HttpClient();
            URI uri = new URI(cmd.toString());
            GetMethod method = new GetMethod(uri.getEscapedURI());
            method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, TIMEOUT);
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(3, false));
            
            int statusCode = client.executeMethod(method);
            
            result = String.valueOf(statusCode);
            
          
        } catch (Exception ex){
            ex.printStackTrace();
        }
        
        return result;
    }   
}


